import {app} from 'electron';
import path from 'path';
import fs from 'fs';
import {fileURLToPath} from 'url';

export default {
    file: {
        /**
         * 基于应用路径获取绝对路径
         * @param filePath 应用路径
         * @return {string} 绝对路径
         */
        getAbsolutePathBasedOnApp(filePath) {
            if (!path.isAbsolute(filePath)) {
                filePath = path.join(app.getAppPath(), filePath);
            }
            return filePath;
        },
        /**
         * 基于相对路径获取绝对路径
         * @param filePath 相对路径
         * @return {*|string} 绝对路径
         */
        getAbsolutePathBasedOnRelative(filePath) {
            if (!path.isAbsolute(filePath)) {
                // 获取当前文件的 URL 并转换为文件系统路径
                let filename = fileURLToPath(import.meta.url);
                // 获取当前文件所在的目录
                let dirname = path.dirname(filename);
                // 构建绝对路径
                return path.resolve(dirname, filePath);
            }
            return filePath;
        },
        loopDir(dir, pathRegex, consumer) {
            if (typeof pathRegex === 'function') {
                consumer = pathRegex;
                pathRegex = undefined;
            }
            if (fs.statSync(dir).isDirectory()) {
                let filenames = fs.readdirSync(dir);
                for (let filename of filenames) {
                    let filePath = path.join(dir, filename);
                    let stats = fs.statSync(filePath);
                    if (stats.isDirectory()) {
                        this.loopDir(filePath, pathRegex, consumer);
                    } else if (stats.isFile()) {
                        if (typeof pathRegex === 'string') {
                            let regex = new RegExp(pathRegex);
                            if (!regex.test(filePath)) {
                                continue;
                            }
                        }
                        consumer(filePath);
                    }
                }
                return true;
            }
            return false;
        },
    },
}
